<?php
/*
 * @project CreativeFramework
 * @version <#RELEASE_VERSION#>
 * @license GNU Lesser General Public License
 * @author Jimmie Lin
 */

/***********************************************
 * This file was not written with MVC in mind
 * as I didn't use Views for any of these (nor models)
 * 
 * Basically, this is a what I call a 'Monolithic' file.
 */

class Config extends CF_Controller {
	function __construct() {
		global $Lang, $UI;
		$this->title = "Configuration";
		$this->desc = "";
		$UI->write_sidebar_head("Settings &amp; Control");
		$UI->write_sidebar_link("/admin.php?app=global&controller=config", "Setting Dashboard", "silk/house.png");
		$UI->write_sidebar_link("/admin.php?app=global&controller=config&act=listgroups", "Setting Groups", "silk/page_white_copy.png");
		$UI->write_sidebar_link("/admin.php?app=global&controller=config&act=apps", "Applications", "silk/plugin.png");
		$UI->write_sidebar_link("/admin.php?app=global&controller=config&act=hooks", "Hooks", "silk/controller.png");
		$UI->write_sidebar_head("Logs");
		$UI->write_sidebar_link("/admin.php?app=global&controller=config&act=acploglogs", "ACP Login Logs", "silk/key.png");
		$UI->write_sidebar_link("/admin.php?app=global&controller=config&act=acplogs", "ACP Logs", "silk/script.png");
	}
	
	// ACP Logs, partically stolen from AcpLogLogs()
	function Acplogs() {
		global $DB, $Smarty, $UI, $Pagination;
		$UI->message("From here you can see the Admin CP Action Logs.", "info");
		// Our page is...
		if(isset($_GET['page'])) $page = $_GET['page'];
		else $page = 1;
		$Logs = $DB->Driver->simple_select("acp_logs", "*", "", array(array("order", "time", "DESC")));
		$pages = $Pagination->calculatePages($DB->Driver->num_rows($Logs), 10);
		$offsets = $Pagination->calculateOffsetXY(10, $page);
		$Logs = $DB->Driver->simple_select("acp_logs", "*", "", array(array("order", "time", "DESC"), array("limit", "{$offsets[0]}, {$offsets[1]}")));
		$log = "";

		while($Log = $DB->Driver->fetch_array($Logs)) {
			$Smarty->assign("Log", $Log);
			if(!isset($this->userarray[$Log["uid"]])) {
				$this->userarray[$Log["uid"]] = $DB->Driver->fetch_array($DB->Driver->simple_select("users", "*", "`id` = '{$Log['uid']}'"));
			}
			// Send it to smarty
			$Smarty->assign("LogUser", $this->userarray[$Log["uid"]]);
			$log .= $Smarty->fetch("global/admin/admin_log_single.tpl");
		}
		echo $UI->basicTable("Admin CP Logs", $log, "silk/key.png", false);
		// Pagination Links
		echo $Pagination->generateLinks("/admin.php?app=global&controller=config&act=acplogs", $page, $pages);
	}
	
	
	// ACP Log In Logs
	function Acploglogs() {
		// What a weird function name, isn't it?
		global $DB, $Smarty, $UI, $Pagination;
		$UI->message("From here you can see the Admin CP Log in Logs.", "info");
		// Our page is...
		if(isset($_GET['page'])) $page = $_GET['page'];
		else $page = 1;
		$LoginLogs = $DB->Driver->simple_select("acp_logins", "*", "", array(array("order", "time", "DESC")));
		$pages = $Pagination->calculatePages($DB->Driver->num_rows($LoginLogs), 10);
		$offsets = $Pagination->calculateOffsetXY(10, $page);
		$LoginLogs = $DB->Driver->simple_select("acp_logins", "*", "", array(array("order", "time", "DESC"), array("limit", "{$offsets[0]}, {$offsets[1]}")));
		$Login_log = "";
		
		while($LoginLog = $DB->Driver->fetch_array($LoginLogs)) {
			$Smarty->assign("LoginLog", $LoginLog);
			if(!isset($this->userarray[$LoginLog["uid"]])) {
				$this->userarray[$LoginLog["uid"]] = $DB->Driver->fetch_array($DB->Driver->simple_select("users", "*", "`id` = '{$LoginLog['uid']}'"));
			}
			// Send it to smarty
			$Smarty->assign("LoginLogUser", $this->userarray[$LoginLog["uid"]]);
			$Login_log .= $Smarty->fetch("global/admin/login_log_single.tpl");
		}
		echo $UI->basicTable("Admin CP Login Logs", $Login_log, "silk/key.png", false);
		// Pagination Links
		echo $Pagination->generateLinks("/admin.php?app=global&controller=config&act=acploglogs", $page, $pages);
	}
	
	// Hooks part
	function Hooks() {
		global $DB, $Smarty, $UI, $Main;
		$UI->message("<b>(Prototype)</b> This is incomplete and more features will be added soon.");
		$UI->message("From here you can see all the Hooks/Event Listeners that are installed on your CF Installation.", "info");
		$HooksQuery = $DB->Driver->simple_select("hooks");
		$output = "";
		while($Array = $DB->Driver->fetch_array($HooksQuery)) {
			$Smarty->assign("hook", $Array);
			$output .= $Smarty->fetch("global/admin/hook_single.tpl");
		}
		if(trim($output) == "")
			$output = $UI->message("Sorry, there are no hooks to display!", "info", true);
		echo $UI->basicTable("Installed Hooks", $output, "silk/controller.png", false);
	}
	
	function DelHook(){
		global $DB, $UI;
		if(!IN_AJAX) {
			if(!isset($_GET['id']))
				$UI->message("Sorry, you must specify an ID!", "error");
			else{
				// Attempt to delete it
				$q = $DB->Driver->delete_query("hooks", array("id", intval($_GET['id'])));
				$UI->redirect("/admin.php?app=global&controller=config",
					2, true,
					"The hook has been deleted. Please wait while we redirect you...", "success");
			}
		}
		else{
			if(!isset($_GET['id']))
				echo "Sorry, this hook was not found!";
			else {
				// Attempt to delete it
				$q = $DB->Driver->delete_query("hooks", array("id", intval($_GET['id'])));
				if(!$q)
					echo "Sorry, this hook was not found!";
				else
					echo "true";
			}
		}
	}
	
	// Application part...
	function Apps(){ $this->Applications(); } // Yeah, redir.
	function Applications() {
		global $DB, $Smarty, $UI, $Main;
		// OK - Go get it!
		// Path is APPLICATION_PATH.universal.
		if($d = opendir(APPLICATION_PATH."universal/")) {
			while(($file = readdir($d)) !== false) {
				if($file !== "." and $file !== ".." and is_dir(APPLICATION_PATH."universal/".$file)) {
					$Main->_convertXmlObjToArr(simplexml_load_file(APPLICATION_PATH."universal/".$file."/application.xml"), $appdata[$file]);
				}
			}
		}
		// OK- show it
		// Foreach operates on a copy of the array therefore
		// we cannot modify it. Silly it is.
		foreach($appdata as $key => $value) {
			$apps[$key]["name"] = $value[0]["children"][1]["text"];
			$apps[$key]["desc"] = $value[0]["children"][2]["text"];
			$apps[$key]["uuid"] = $value[0]["children"][0]["text"];
			$apps[$key]["author"] = $value[0]["children"][3]["text"];
			$apps[$key]["version"] = $value[0]["children"][4]["text"];
			$apps[$key]["key"] = $value[0]["children"][5]["text"];
			$apps[$key]["icon"] = $value[0]["children"][6]["text"];
			$apps[$key]["xml"] = $value;
		}
		
		/* Originally
		foreach($appdata as $key => $value) {
			// Parse it...
			// $appdata[$key]
			$data = simplexml_load_string($value);
			$appdata[$key]["name"] = $data->info->title;
			$appdata[$key]["uuid"] = $data->info->uuid;
			$appdata[$key]["author"] = $data->info->author;
			$appdata[$key]["version"] = $data->info->version;
			$appdata[$key]["key"] = $data->info->key;
			$appdata[$key]["xml"] = $data;
		} */
		
		// Now that we're all set, output
		$UI->message("From here, you can see what applications are present on your CF Installation.", "info");
		$UI->message("This page shows all applications available on your system. If you find any application that you didn't install and/or is suspicious, investigate it immediately.");
		// nice_dump($apps); // Testing code
		$output = "";
		foreach($apps as $key => $val) {
			$Smarty->assign("app", $val);
			$output .= $Smarty->fetch("global/admin/app_single.tpl");
		}
		// Get it out
		echo $UI->basicTable("Installed Applications", $output, "silk/plugin.png", false);
	}
	
	/*
	 *************** CONFIGURATION
	 */
	
	function SubmitConfGroup() {
		global $DB, $Smarty, $UI, $IN, $Main;
		// OK. Start updating settings,
		if(!isset($_GET["k"])) { // Silly you,
			$UI->message("Sorry, you're not supposed to be here!", "error");
		}
		else {
			// So...Let's see. Get group,
			$q = $DB->Driver->simple_select("config_groups", "*", "`key` = '{$_GET['k']}'");
			if($DB->Driver->num_rows($q) == 0) {
				$UI->message("Sorry, this configuration group was not found...", "error");
			}
			else {
				// Now get all configs.
				$q = $DB->Driver->simple_select("configs", "*", "`group` = '{$_GET['k']}'");
				while($a = $DB->Driver->fetch_array($q)) {
					if(isset($_POST[$a['key']])) {
						// is it the same?
						if($_POST[$a['key']] == $a['value']) {
							// Oh bah, skip
						}
						else {
							$Main->update_config_value($a['key'], $_POST[$a['key']]);
						}
					}
				}
				// Done? Log
				$Main->write_acp_log("Configuration Values updated");
				$UI->redirect(
					"/admin.php?app=global&controller=config&act=listgroups",
					2,
					true,
					"Configuration values updated. Please wait while we're redirecting you...",
					"success"
				);
			}
		}
	}
	
	function Listgroups() {
		global $DB, $Smarty, $UI;
		$UI->message("From here you can configure your system in multiple parts - choose a setting group to start with.", "info");
		$output = "";
		$q = $DB->Driver->simple_select("config_groups");
		while($a = $DB->Driver->fetch_array($q)) {
			$Smarty->assign("confgroup_key", $a['key']);
			$Smarty->assign("confgroup_title", $a['title']);
			$Smarty->assign("confgroup_desc", $a['desc']);
			$output .= $Smarty->fetch("global/admin/confgroup.tpl");
		}
		echo $UI->basicTable("Configuration Groups", $output, "silk/wrench.png");
	}
	
	function Viewsetgroup() {
		global $DB, $Smarty, $UI, $IN;
		$UI->message("You can configure this setting group's settings here.");
		$output = "";
		if(!isset($_GET['k'])) header("Location: admin.php?app=global&controller=dashboard");
		$k = $IN->str_only($_GET['k']);
		$Smarty->assign("k", $k);
		$q = $DB->Driver->simple_select("configs", "*", "`group` = '{$k}'");
		if($DB->Driver->num_rows($q) == 0) {
			$output = $UI->message("Sorry, there are no configuration values in this group!", "error", true);
		}
		else {
			while($a = $DB->Driver->fetch_array($q)) {
				$Smarty->assign("conf", $a);
				$output .= $Smarty->fetch("global/admin/conf_single.tpl");
			}
		}
		if(trim($output) == "") {
			$output = $UI->message("Sorry, there are no configuration values in this group!", "error", true);
			$begin = ""; $end = $Smarty->fetch("global/admin/confsingle_none_end.tpl");
		}
		else {
			$begin = $Smarty->fetch("global/admin/confsingle_begin.tpl");
			$end = $Smarty->fetch("global/admin/confsingle_end.tpl");
		}
		echo $UI->basicTable("Settings for Group '{$k}'", $begin.$output.$end, "silk/cog.png", false);
	}
	
	function Index() {
		global $UI;
		$UI->message("<b>(Post-Beta)</b> This would probably contain some tips & tricks, etc...");
		$UI->message("Welcome to your configuration area. From here you can configure your CF Installation and see the installed modules.", "info");
	}
}
